package sub_table

import (

	"errors"
	"fmt"
	MgoPool "gitee.com/tym_hmm/mgo-pool"
	"strings"
	"sync"
)

type modelMgoNotifyTask struct {
	MgoPool.BaseMgoManyModel
	FieldNotifyTask

	dateTime    string
	tableExists map[string]bool
	ml          sync.Map
}

var modelMgoNotifyTaskOnce sync.Once
var modelMgoNotifyTaskApi *modelMgoNotifyTask

func NewModelMgoNotifyTask() *modelMgoNotifyTask {
	modelMgoNotifyTaskOnce.Do(func() {
		modelMgoNotifyTaskApi = &modelMgoNotifyTask{tableExists: make(map[string]bool)}
	})
	return modelMgoNotifyTaskApi
}

/**
设选择使用哪个builderName 必须指定
*/
func (this *modelMgoNotifyTask) Build() error {
	//beaConfig := Core.BeanFactory.GetName("BeanConf").(*Core.BeanConf)
	//c, err := beaConfig.GetConf()
	//if err != nil {
	//	Log.AppLog.Error("modelMgoNotifyTask build error %s", err.Error())
	//	return err
	//}
	//获取抽奖的数据库连接
	//this.SetBuildName(c.GetMongodbServer().BuilderName)
	return nil
}

/*********分表开始************/
/**
设置分表时间戳 如20220513
*/
func (this *modelMgoNotifyTask) SetDateTime(dateTime string) {
	this.dateTime = dateTime
}

func (this *modelMgoNotifyTask) GetDateTime() string {
	return this.dateTime
}

/**
@param dateTime  string 设置表的时间 如:20220513
@param lastDateTime string 设置表时间前一天 如:20220512
*/
func (this *modelMgoNotifyTask) ClearTableCache(dateTime string, lastDateTime string) {
	if this.tableExists != nil && len(this.tableExists) > 0 {
		//nowTableName := t.TableNameCus(dateTime)
		lastLastTime := this.GetSeparateCollection(lastDateTime)
		//Log.AppLog.Debug("清除集合缓存, tableExists [lastTableName => %s] 之前的缓存集合", lastLastTime)
		for k, _ := range this.tableExists {
			if k == lastLastTime {
				continue
			} else {
				delete(this.tableExists, k)
			}
		}
	}
}

/**
预生成集合
mgo通过创建索引来创建集合
*/
func (this *modelMgoNotifyTask) PreCreateNextStrip() error {
	err := this.Build()
	if err != nil {
		return err
	}
	collectionName := this.GetSeparateCollection(this.dateTime)
	_, oks := this.ml.LoadOrStore(collectionName, "1")
	defer this.ml.Delete(collectionName)
	if !oks {
		if _, ok := this.tableExists[collectionName]; !ok {
			session, db, errMgo := this.GetSessionOnly()
			if errMgo != nil {
				return errors.New(errMgo.Error())
			}
			defer session.Close()
			c := db.C(collectionName)
			_, err = c.Indexes()
			if err != nil { //通过判断是否存在索引
				if strings.Contains(strings.TrimSpace(err.Error()), "ns does not exist") {
					//如果不存在表
					//创建索引
					indexKey := this.IndexKey()
					for _, v := range indexKey {
						err := c.EnsureIndex(v)
						if err != nil {
							//Log.AppLog.Error("create index collectionName [%s] error [ err =>%+v ]", collectionName, err)
							return err
						}
					}
					this.tableExists[collectionName] = true
				} else {
					//Log.AppLog.Error("get  collectionName [%s] error [ err =>%+v ]", collectionName, err)
					return err
				}
			}
		}
	}
	return nil
}

/*********分表结束************/
/**
写入一条数据
*/
func (this *modelMgoNotifyTask) InsertRow(dataField *FieldNotifyTask) error {
	err := this.Build()
	if err != nil {
		fmt.Println("err1", err)
		return err
	}
	session, db, errMgo := this.GetSessionOnly()
	if errMgo != nil {
		fmt.Println("err2", errMgo)
		return err
	}
	defer session.Close()
	err = db.C(this.GetSeparateCollection(this.dateTime)).Insert(&dataField)
	if err != nil {
		fmt.Println("err3", err)
		return err
	}
	return nil

}

// id从1开始递增
//func GenId(db *mgo.Database) (int64, error) {
//	  IDInt64 := struct {
//		     Value int64 `bson:"max_id"`
//		  }{Value: 1}
//	  _, err := db.C("gen_id").Find(bson.M{}).Apply(mgo.Change{Update: bson.M{"$inc": IDInt64}, Upsert: true, ReturnNew: true}, &IDInt64)
//	  return IDInt64.Value, err
//}
